import MonacoEditor, { OnMount } from "@monaco-editor/react";
import { useEffect, useState } from "react";
import { useComponentsStore } from "@editor/stores/components";

export interface CustomJsConfig {
    type: 'customJS'
    code: string
}

export interface CustomJsProps {
    value?: string
    defaultValue?: string
    onChange?: (config: CustomJsConfig) => void
}

export const CustomJs = ({ defaultValue, onChange, value: val }: CustomJsProps) => {
    const [value, setValue] = useState<string>(defaultValue||'');
    const { curComponentId } = useComponentsStore();

    const handleEditorMount: OnMount = (editor, monaco) => {
        editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyJ, ()=>{
            editor.getAction('editor.action.formatDocument')?.run();
        })
    }
    const codeChange = (value?: string) => {
        if(!curComponentId) return;
        setValue(value||'');
        onChange?.({
            type: 'customJS',
            code: value!
        })
    }

    useEffect(()=>{
        setValue(val||'')
    }, [val])

    return (
        <div className="mt-[40px] flex items-start gap-[20px]">
            <div>自定义 JS</div>
            <div>
                <MonacoEditor width={'600px'}
                height={'400px'}
                path="action.js"
                language="javascript"
                onMount={handleEditorMount}
                onChange={codeChange}
                value={value}
                options={{
                    fontSize: 14,
                    scrollBeyondLastLine: false,
                    minimap: { enabled: false },
                    scrollbar: {
                        verticalScrollbarSize: 6,
                        horizontalScrollbarSize: 6
                    }
                }} />
            </div>
        </div>
    )
}